package com.setup.trac.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.setup.trac.pojo.Utenti;
import com.setup.trac.pojo.wrappers.UtentiView;
import com.setup.trac.service.AdminService;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.TracSetupUtil;

public class ChangePasswordController extends LoginFormController {

	
	private SearchService searchService;
	private AdminService adminService;
	private TracSetupUtil tracSetupUtil;
	@Override
	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		UtentiView uv = (UtentiView)command;
		Utenti user = uv.getUtenti();
		user.setPassword(getTracSetupUtil().md5(uv.getUtenti().getUsername()+uv.getNewPassword()));
		user.setPrimoAccesso(false);
		getAdminService().updateUser(user);
		user.setPassword(uv.getNewPassword());
		uv.setUtenti(user);
		command = uv;
		return super.onSubmit(request, response, command, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {
		ModelAndView mav = super.showForm(request, response, errors, controlModel);
		
		return mav;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public AdminService getAdminService() {
		return adminService;
	}

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		HttpSession session = request.getSession(false); 
		return session.getAttribute("loginForm")==null? super.formBackingObject(request):session.getAttribute("loginForm");
		
		
	}

	public TracSetupUtil getTracSetupUtil() {
		return tracSetupUtil;
	}

	public void setTracSetupUtil(TracSetupUtil tracSetupUtil) {
		this.tracSetupUtil = tracSetupUtil;
	}
	
}
